//
//  UpgradeView.m
//  Router
//
//  Created by teki on 16/3/3.
//  Copyright © 2016年 dc. All rights reserved.
//

#import "UpgradeView.h"
#import "WIFIManagerTableViewCell.h"
#import "WIFIHelper.h"
#import "AFNetworkReachabilityManager.h"
#import "UpgradeFinishView.h"

#define SHOW_NUMBERS (5)

@interface UpgradeView ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentHeight;
@property (nonatomic, strong) WIFIHelper *wifiHelper;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *contentTableViewTop;

@property (nonatomic, strong) NSMutableArray *needUpdateArray;

@end

@implementation UpgradeView
- (void)awakeFromNib
{
    
    self.contentView.backgroundColor = RGB(240, 244, 233);
    self.contentView.layer.cornerRadius = 5.0f;
    self.contentView.layer.masksToBounds = YES;
    
    self.upgradeBtn.layer.cornerRadius = 5.0f;
    self.upgradeBtn.layer.masksToBounds = YES;
    
    self.tableView.separatorInset = UIEdgeInsetsZero;
    [self.tableView registerClass:[WIFIManagerTableViewCell class] forCellReuseIdentifier:@"upgardeCellIdentifier"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    [self.upgradeBtn setBackgroundImage:[UIImage imageWithColor:RGB(144, 144, 144)] forState:UIControlStateDisabled];
    [self.upgradeBtn setBackgroundImage:[UIImage imageWithColor:RGB(79, 152, 68)] forState:UIControlStateNormal];
    
    UIImageView *closeView = [[UIImageView alloc]init];
    closeView.image = [UIImage imageNamed:@"device_close"];
    [self.contentView addSubview:closeView];
    [closeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.contentView).offset(-10);
        make.width.and.height.mas_equalTo(30);
        make.top.mas_equalTo(self.contentView);
    }];
    
    UIButton *closeBtn = [[UIButton alloc]init];
    [self.contentView addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.and.top.mas_equalTo(closeView);
        make.width.mas_equalTo(85);
        make.height.mas_equalTo(30);
    }];
    [closeBtn addTarget:self action:@selector(dismiss2) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.stations count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WIFIManagerTableViewCell *cell = (WIFIManagerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"upgardeCellIdentifier"];
    cell.separatorInset  = UIEdgeInsetsZero;
    cell.upgradeModel = self.stations[indexPath.row];
    return cell;
}

#pragma mark -
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}





- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark -
#pragma mark   升级
- (IBAction)upgrade:(id)sender {
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    
    NSMutableArray *managers = [NSMutableArray array];
    for (int i=0; i< [self.needUpdateArray count]; i++) {
        __block StationModel *model = self.needUpdateArray[i];
        RequestManager *manager = nil;
        NSDictionary *version = model.versionInfo;
        NSString *fileUrl = version[@"file_url"];
        if (version && fileUrl)
        {
            if (model.master) {
                manager = [self.wifiHelper getUpgradeMotherCatWithDeviceID:model.device_id fileURL:fileUrl success:^(BOOL succ, id responseObject, NSString *msg) {
                    
                } failure:^(NSError *error) {
                    
                }];
            }
            else{
                manager = [self.wifiHelper getUpgradeSonCatWithDeviceID:model.device_id masterDeviceID:wifi.device_id fileURL:fileUrl success:^(BOOL succ, id responseObject, NSString *msg) {
                    
                } failure:^(NSError *error) {
                    
                }];
            }
            [managers addObject:manager];
        }
        //队列请求
        WEAKSELF
        [self.wifiHelper requestGroupWithManagers:managers completion:^{
            [weakSelf dismiss];
            [weakSelf showFinishView];
        }];
    }
    
}


- (void)showFinishView
{
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"UpgradeFinishView" owner:nil options:nil];
    UpgradeFinishView *finishView = (UpgradeFinishView *)array[0];
    [finishView showInView:[UIApplication sharedApplication].keyWindow];
}



- (IBAction)backViewDidTap:(id)sender {
    [self dismiss];
}



- (void)showInView:(UIView *)view
{
    [view addSubview:self];
    [self makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(view);
    }];
    
    NSInteger count = [self.stations count];
    if (count > SHOW_NUMBERS)
    {
        count = SHOW_NUMBERS;
    }

    self.contentHeight.constant = count * 44 + 50 + 30;
    self.contentTableViewTop.constant = 30;
    
    self.upgradeBtn.enabled = NO;
}






- (void)check
{
    if ([AFNetworkReachabilityManager sharedManager].reachable) {
        __weak __typeof(self)weakSelf = self;
        [self dispatchTimerWithTime:0.25 block:^{
            [weakSelf checkUpgrade];
        }];
    }
    else{
        [self showToastText:@"当前网络已断开!"];
    }
}


- (void)checkUpgrade
{
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;

    __block BOOL hasUpgrade  = 0;
    NSMutableArray *managers = [NSMutableArray array];
    for (int i=0; i< [self.stations count]; i++) {
        __block StationModel *model = self.stations[i];

        if (model.wifi_enable) {
            model.type = UpgradeTypeScaning;
        }
        else{
            model.type = UpgradeTypeOffLine;
        }
                
        [self.needUpdateArray removeAllObjects];
        
        [self.tableView reloadData];
        WEAKSELF
        //返回请求对象
        RequestManager *manager = [self.wifiHelper getCheckUpdateWithDeviceID:model.device_id masterDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
            if (responseObject) {
                NSInteger code = [responseObject[@"code"] integerValue];
                NSDictionary *version = responseObject[@"version"];
                BOOL hasNew = [version[@"has_new"] intValue] == 1;
                
                if (code == 0 && version && hasNew)
                {
                    model.type = UpgradeTypeHasNewVersion;
                    hasUpgrade = 1;
                    model.versionInfo = version;
                    [self.needUpdateArray addObject:model];
                }else{
                    model.type = UpgradeTypeNewest;
//                    [self showToastText:@"设备软件已是最新版本!"];
                }
            }
            else{
                model.type = UpgradeTypeOffLine;
            }
            [weakSelf.tableView reloadData];
        } failure:^(NSError *error) {
            model.type = UpgradeTypeOffLine;
            [weakSelf.tableView reloadData];

            
        }];
        [managers addObject:manager];
    }
    
    //队列请求
    [self.wifiHelper requestGroupWithManagers:managers completion:^{
        if (hasUpgrade) {
            self.upgradeBtn.enabled = YES;
        }else{
            self.upgradeBtn.enabled = NO;
        }
    }];
}


- (void)dismiss
{
//    [UIView animateWithDuration:0.25 animations:^{
//        self.alpha = 0.0f;
//    } completion:^(BOOL finished) {
//        [self removeFromSuperview];
//    }];
}

- (void)dismiss2
{
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}



- (WIFIHelper *)wifiHelper
{
    if (_wifiHelper == nil)
    {
        _wifiHelper = [[WIFIHelper alloc] init];
    }
    return _wifiHelper;
}


- (NSMutableArray *)needUpdateArray
{
    if (!_needUpdateArray)
    {
        _needUpdateArray = [[NSMutableArray alloc] init];
    }
    return _needUpdateArray;
}
@end
